/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import { message, Select } from 'antd';
import { searchShop, resetShop } from '@/services/tools/orderManage';
import { ModalForm } from '@ant-design/pro-form';
import { Popconfirm, Button } from 'antd';
import React, { useState } from 'react';

const { Option } = Select;

interface RefuseModalProps {
  children: JSX.Element;
  item: any;
  getOrderDetails: Function;
}

interface SEARCHOPTIONS {
  index_shop_name: string;
  index_shop_id: string;
}

const fetch = (
  value: string,
  brand: string,
  callback: (data: { value: string; text: string }[]) => void,
) => {
  searchShop({ name: value, brand: brand }).then((res) => {
    console.log(res, ';re');
    const { code, data, msg } = res;
    if (code == 0) {
      const list = data.map((item: SEARCHOPTIONS) => ({
        text: item.index_shop_name,
        value: item.index_shop_id,
      }));
      callback(list);
    } else {
      message.error(msg);
    }
  });
};

const Index: React.FC<RefuseModalProps> = ({ item, children, getOrderDetails, ...rest }) => {
  const [data, setData] = useState<any[]>([]);
  const [value, setValue] = useState<string>();
  const { brand } = item;
  const handleSearch = (newValue: string) => {
    if (newValue) {
      fetch(newValue, brand, setData);
    } else {
      setData([]);
    }
  };

  const handleChange = (newValue: string) => {
    setValue(newValue);
  };

  const options = data.map((d) => <Option key={d.value}>{d.text}</Option>);

  return (
    <ModalForm
      {...rest}
      title='温馨提示'
      trigger={children}
      width={540}
      onFinish={async () => {
        if (!value) {
          message.error('请输入网点信息');
          return;
        }
        return resetShop({ shopID: value, orderNo: item.id }).then(({ code, msg }) => {
          if (code == 0) {
            message.success(msg);
            getOrderDetails();
            setValue('');
            return true;
          }
          message.error(msg);
          return false;
        });
      }}
      submitter={{
        render: (props) => [
          <Popconfirm title='你确定分配到以下网点吗？' key='pass' onConfirm={() => props.submit()}>
            <Button type='primary'>确定</Button>
          </Popconfirm>,
        ],
      }}
    >
      <h4>分配到一下网点：</h4>
      <Select
        showSearch
        value={value}
        placeholder='请输入网点'
        style={{ width: '100%' }}
        defaultActiveFirstOption={false}
        showArrow={false}
        filterOption={false}
        onSearch={handleSearch}
        onChange={handleChange}
        notFoundContent={null}
      >
        {options}
      </Select>
    </ModalForm>
  );
};

export default Index;
